package com.hzy.login;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Paint;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.hzy.listview.NotepadListActivity;
import com.hzy.text.R;

/**
 * Created by Administrator on 2016/6/22 0022.
 */
public class LoginFragment extends BaseFragment{
    private static LoginFragment self;

    private EditText editText_1,editText_2;
    private Button loginBtn,registerBtn;
    private String userName;
    private String userCode;
    private UserDBHelper userDBHelper;
    public LoginFragment(){
       super(R.layout.fragment_login);
    }

    public static synchronized LoginFragment getInstance(){
        if (self == null) self =new LoginFragment();
        return self;
    }

    @Override
    protected void findView() {
        editText_1 = (EditText) findViewById(R.id.edit_1);
        editText_2 = (EditText) findViewById(R.id.edit_2);
        loginBtn = (Button) findViewById(R.id.login_btn);
        registerBtn = (Button) findViewById(R.id.login_register_btn);
    }

    @Override
    protected void initView() {

        userDBHelper =new UserDBHelper(getActivity(),"User.db",null,1);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                userName = editText_1.getText().toString();
                userCode = editText_2.getText().toString();

                if (userName == null || userCode == null ){
                    Toast.makeText(getActivity(),"请输入账号和密码",Toast.LENGTH_SHORT).show();
                } else {
                    SQLiteDatabase db = userDBHelper.getWritableDatabase();
                    Cursor cursor = db.rawQuery("select * from User where userName = ?",new String[]{userName});
                    if (cursor.moveToFirst()){
                        if (userCode.equals(cursor.getString(cursor.getColumnIndex("userCode")))){
                            Intent intent = new Intent(getActivity(), NotepadListActivity.class);
                            intent.putExtra("userName",userName);
                            startActivity(intent);
                            
                        }  else {
                            Toast.makeText(getActivity(),"账号或密码错误",Toast.LENGTH_SHORT).show();
                        }
                        cursor.close();
                    } else {
                        Toast.makeText(getActivity(),"请注册账号",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
        registerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(getActivity(),RegisterActivity.class);
                startActivity(it);
            }
        });
    }
}
